package com.aofeng.hybridwork.android.bluetooth.sdk;

import java.util.Set;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Handler;
import android.os.Message;

/**
 * 蓝牙打印
 */
public class BTPrint {
	private BluetoothAdapter mBtAdapter;

	private BluetoothService mService;

	@SuppressLint("HandlerLeak")
	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {

		}
	};

	public BTPrint() {
		mBtAdapter = BluetoothAdapter.getDefaultAdapter();
		mService = new BluetoothService(mHandler);
	}

	/**
	 * 打开蓝牙
	 */
	public void open() {
		if (!mBtAdapter.isEnabled()) {
			mBtAdapter.enable();
		}

		if (mService != null) {
			if (mService.getState() == BluetoothService.STATE_NONE) {
				mService.start();
			}
		}
	}

	/**
	 * 获取已匹配的设备列表
	 */
	public Set<BluetoothDevice> getBondedDevices() {
		if (mBtAdapter != null) {
			return mBtAdapter.getBondedDevices();
		}
		return null;
	}

	/**
	 * 连接蓝牙
	 * 
	 * @param macAddress
	 *            设备MAC地址
	 */
	public void connect(String macAddress) {
		mBtAdapter.cancelDiscovery();
		if (BluetoothAdapter.checkBluetoothAddress(macAddress)) {
			BluetoothDevice device = mBtAdapter.getRemoteDevice(macAddress);
			mService.connect(device);
		}
	}

	/**
	 * 发送数据
	 * 
	 * @param msg
	 *            打印数据
	 */
	public void PrintData(String msg) throws Exception {
		if (mService.getState() != BluetoothService.STATE_CONNECTED) {
			throw new Exception("蓝牙连接不可用");
		}
		mService.write(msg.getBytes("GBK"));
		mService.write(new byte[] { 0x0a, 0x0a, 0x0a, 0x0a });
	}

	/**
	 * 关闭蓝牙
	 */
	public void close() {
		if (mService != null)
			mService.stop();
		if (mBtAdapter != null)
			mBtAdapter.cancelDiscovery();
	}

}
